package com.celesea.configuration.security;

import com.alibaba.fastjson.JSON;
import com.celesea.configuration.security.bean.AuthorityUser;
import com.celesea.configuration.security.bean.SsoLoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class CasRedisProvider {

    private static Logger logger = LoggerFactory.getLogger(CasRedisProvider.class);

    @Qualifier("casRedisTemplate")
    @Autowired
    private StringRedisTemplate casRedisTemplate;

    public AuthorityUser getUserInfoFromRedis(String loginSessionId) {
        logger.info("======================================>>");
        logger.info("开始从Redis获取用户信息：loginSessionId：{}", loginSessionId);
        String redisUserKey = SsoUtil.getLoginInfoKey(loginSessionId);
        String loginInfo = readRedis(redisUserKey);
        if (StringUtils.isEmpty(loginInfo)) {
            return null;
        }
        SsoLoginInfo ssoLoginInfo = JSON.parseObject(loginInfo, SsoLoginInfo.class);
        AuthorityUser userDetails = new AuthorityUser(ssoLoginInfo, getUserUpdateTime(loginSessionId));
        logger.info("----->>>>>>:{}", ssoLoginInfo.getPermissionCollection());

        return userDetails;
    }

    public Long getUserUpdateTime(String loginSessionId) {
        String updateTimeKey = SsoUtil.getUpdateTimeKey(loginSessionId);
        String updateTime = readRedis(updateTimeKey);
        try {
            return Long.valueOf(updateTime);
        } catch (Exception e) {
            return -1L;
        }
    }

    private String readRedis(String token) {
        ValueOperations<String, String> redisOperation = this.casRedisTemplate.opsForValue();
        return redisOperation.get(token);
    }

}
